#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Copyright © 2019-present Lenovo

This file is licensed under both the BSD-3 license for individual/non-commercial use and
EPL-1.0 license for commercial use. Full text of both licenses can be found in
COPYING.BSD and COPYING.EPL files.
"""

import logging.config
import pika
from paste.deploy import loadapp


logging.config.fileConfig('/etc/antilles/antilles.ini')

logger = logging.getLogger(__name__)
logger.info("start the job daemon")

loadapp('config:antilles.ini#django', relative_to='/etc/antilles')

# 0
# get cluster domain name from the cluster config file under etc
from job_daemon.dispatcher import Dispatcher
from django.conf import settings

# clean garbage
from libs.util.dbutil import DBUtil

retdata = {}
retdata["method"] = "clean_job_dirty_data"
retdata["args"] = {}
DBUtil().invoke_save(retdata)

# 1, initiate services
dispatcher = Dispatcher()

# 2, start listening tasks from MQ
connection = pika.BlockingConnection(pika.URLParameters(settings.BROKER_URL))
channel = connection.channel()
# channel.exchange_declare(exchange="openhpc", exchange_type="topic")
# channel.queue_declare(queue='job', durable=True)
# channel.queue_bind(exchange='openhpc', queue='job', routing_key="job")


def callback(ch, method, properties, body):
    try:
        logger.debug("New message is received: %s", body)
        dispatcher.handle(str(body))
    finally:
        ch.basic_ack(delivery_tag=method.delivery_tag)
        logger.debug("Message is acknowledged.")


channel.basic_consume(callback, queue='job')
channel.start_consuming()
